/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedBean.TX.CustomerIOTRPortal;


import Web_Helper.EmailSender;
import session.TX.*;
import entity.*;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import session.CM.PortalManagementSB;

/**
 *
 * @author Chen Zhe
 */
@ManagedBean (name="fakeMainPortalMB")
@SessionScoped
public class FakeMainPortalMB implements Serializable{

    /** Creates a new instance of FakeMainPortalMB */
    public FakeMainPortalMB() { 
    }
    @EJB
    private PortalManagementSB portalManagementSB;
    
    @EJB
    private ShoppingCartSBRemote cartManager;
    public ShoppingCartSBRemote getCartManager() {return cartManager;}
    
    @EJB
    private UsersSBRemote userManager;
    
//    @EJB
//    private SchedulerSBRemote schedulerBean;
    
    @EJB
    private OutletSBRemote outletManager;
    
    @EJB
    private StakeholderAccountSBRemote stakeholderManager;
    
    @EJB
    private ULPSBRemote ULPManager;
    public ULPSBRemote getULPManager() {return ULPManager;}
    
    private Long customerID = new Long(0);
    private String loginEmail = "N/A";
    private String outletName;
    private String stakeholderName;
    private Long outletId;
    private Long selectedReward_id;
    
    
    public String retrieveAccountType(){
        
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
        if(session.getAttribute("accountType")==null) return "None";
        else return (String)session.getAttribute("accountType");

    }
    
    
    //Code to remove all the above session attributes, simulates a "logout"
    public void removeAllSessionAttributes() {
        System.out.println("Purging all session attributes...");
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
        
        Enumeration<String> attributesList = session.getAttributeNames();
        
        while(attributesList.hasMoreElements()){
            String attributeName = attributesList.nextElement();
            System.out.println("REMOVING ATTRIBUTE: " + attributeName + "    VALUE: " + session.getAttribute(attributeName));
            session.removeAttribute(attributeName);
        }
        
        System.out.println("All session attributes removed...");
    }
    
    
    
    public void adminLogin(){
                FacesContext facesContext = FacesContext.getCurrentInstance();
                HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);    
                session.setAttribute("accountId", 0);
                session.setAttribute("accountType", "admin");
    }
    
    
    
    public void stakeholderLogin(String stakeholderName){
        
        //Find the Stakeholder
        List<Stakeholder> stakeholderList = stakeholderManager.getAllStakeholders();

        for(Stakeholder o: stakeholderList){
            if(o.getName().equalsIgnoreCase(stakeholderName)){
                
                FacesContext facesContext = FacesContext.getCurrentInstance();
                HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);    
                session.setAttribute("stakeholderName", stakeholderName);
                session.setAttribute("stakeholderId", o.getId());           //The primary key of the stakeholder entity
                session.setAttribute("accountType", "representative");
                session.setAttribute("accountId", new Long(9999)); customerID = new Long(9999);
                session.setAttribute("email", loginEmail);

            }
        } 
    }//------------------------------------------------------------------------------------------------------
    
    
    
    
    public void outletLogin(Long outletID){
        
        //Find the Outlet
        List<Outlet> outletList = outletManager.getAllOutlets();

        for(Outlet o: outletList){
            if(o.getId().equals(outletID)){
                
                FacesContext facesContext = FacesContext.getCurrentInstance();
                HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);    
                session.setAttribute("outletId", o.getId());
                session.setAttribute("outletName", o.getOutletName());
                session.setAttribute("outletOwner", o.getStakeholder().getName());
                session.setAttribute("accountId", new Long(9999)); customerID = new Long(9999);
                session.setAttribute("accountType", "foodOutletManager");

            }
        } 
    }//------------------------------------------------------------------------------------------------------
    
    public void custEnterOutlet(Long outletID) {

        //Find the Outlet
        List<Outlet> outletList = outletManager.getAllOutlets();
        

        for (Outlet o : outletList) {
            if (o.getId().equals(outletID)) {
                FacesContext facesContext = FacesContext.getCurrentInstance();
                HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
                session.setAttribute("custOutletId", o.getId());
                session.setAttribute("custOutletName", o.getOutletName());
                System.out.println("custOutletId" + o.getId());
                System.out.println("custOutletname" + o.getOutletName());
            }
        }
        
    }//------------------------------------------------------------------------------------------------------
    
    
    
    //Randall 12-OCT-2011 1531hrs
    /*Login method used temporarily for testing purpose, code derived from SM team
    * The way they do it is to push an attribute into the session, the customer ID (a Long type)
    * with the attribute name "Sid", this keeps track of which customer is currently logged in.
    */
    public void login(){
        System.out.println(">>> fakeMainPortalMB: Login sequence initiated");
        customerID = new Long(0); //take the default to be 0 for the moment.
        
        List<Users> userList = userManager.getAllUser();
        
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
        session.setAttribute("accountType", "user"); 
        session.setAttribute("accountId", 0); //Initialise to dummy value
        
        for(Users o: userList){
            if(o.getEmail().equalsIgnoreCase(loginEmail)){
                System.out.println(">>> fakeMainPortalMB: user account found: " + o.getEmail() + "    ID: " + o.getId());
                customerID = o.getId();
                loginEmail= o.getEmail();

                session.setAttribute("accountId", o.getId());
                session.setAttribute("email", o.getEmail());
                break;
            }
        } 

        
        System.out.println(">>> fakeMainPortalMB: customer logged in: " + session.getAttribute("accountId"));
        System.out.println(">>> Session ID: " + session.getId());
    }
    
    
    
    //-----------------------------------------------------------------------------------------------------------------------------
    //Billing Controls
//    public void startBilling(){
//        schedulerBean.enableBilling();
//    }
//    public void stopBilling(){
//        schedulerBean.disableBilling();
//    }
//    
//    public void enableDemoBilling(){
//        schedulerBean.enableDemoBilling();
//    }
//    public void disableDemoBilling(){
//        schedulerBean.disableDemoBilling();
//    }
//    
//    public String getBillingStatus(){
//        return schedulerBean.getBillingStatus();
//    }
    //-----------------------------------------------------------------------------------------------------------------------------
    
    
//    public void sendTestMail() throws Exception{
//        String senderEmail = portalManagementSB.getEmailFrom();
//        String senderPassword = portalManagementSB.getEmailPassword();
//        EmailSender emailsender = new EmailSender(senderEmail, senderPassword);
//        String[] recepients = {"xatucorp@hotmail.com"};
//        emailsender.postMail( recepients, "subject", "Message......", "foodsage.tcube@gmail.com");
//    }
    
    
    
    
    
    //Randall 12-OCT-2011 1650hrs
    //Used for the Main page, show all the users in the DB, choose one to login
    public List<String> getAllUserEmails(){
        List<String> returnList = new ArrayList<String>();   
        List<Users> userList = userManager.getAllUser(); 
        if (userList == null || userList.isEmpty())
            return null;
        for(Users o: userList){
            returnList.add(o.getEmail());
        }
        return returnList;
    }
    
    
    public List<Outlet> getOutletsbyStakeholder(){
        List<Outlet> returnList = outletManager.getOutletByStakeholder(stakeholderName);      
        return returnList;
    }
    
    
    public List<String> getAllFoodStakeholderNames(){       
        List<String> returnList = new ArrayList<String>();
        
        for(Stakeholder o : stakeholderManager.getAllStakeholders()){
            if (o.getClass() == StakeholderFood.class)
            returnList.add(o.getName());
        }
        
        return returnList;
    }

    
    
    //=============================================================================================================================================
    //Randall Added: Code for ULP functions
    //=============================================================================================================================================

    
    
    public Integer getUserLoyaltyPoints(){
        List<Users> userList = userManager.getAllUser();
        if (userList == null)
            return null;
        
        for(Users o: userList){
            if(o.getEmail().equalsIgnoreCase(loginEmail)){
                System.out.println(">>> fakeMainPortalMB: user account found: " + o.getEmail() + "    Loyalty Points: " +  o.getLoyaltypoint() );
                return o.getLoyaltypoint();
            }
        }
        return 0;
    }
    
    
    
    //=============================================================================================================================================


    /**
     * @return the loginEmail
     */
    public String getLoginEmail() {
        return loginEmail;
    }

    /**
     * @param loginEmail the loginEmail to set
     */
    public void setLoginEmail(String loginEmail) {
        this.loginEmail = loginEmail;
    }

    /**
     * @return the outletName
     */
    public String getOutletName() {
        return outletName;
    }

    /**
     * @param outletName the outletName to set
     */
    public void setOutletName(String outletName) {
        this.outletName = outletName;
    }

    public Long getOutletId() {
        return outletId;
    }

    public void setOutletId(Long outletId) {
        this.outletId = outletId;
    }


    public String getStakeholderName() {
        return stakeholderName;
    }

    public void setStakeholderName(String stakeholderName) {
        this.stakeholderName = stakeholderName;
    }
    
    /**
     * @return the customerID
     */
    public Long getCustomerID() {
        return customerID;
    }

    /**
     * @param customerID the customerID to set
     */
    public void setCustomerID(Long customerID) {
        this.customerID = customerID;
    }

    /**
     * @param cartManager the cartManager to set
     */
    public void setCartManager(ShoppingCartSBRemote cartManager) {
        this.cartManager = cartManager;
    }

    /**
     * @return the selectedReward_id
     */
    public Long getSelectedReward_id() {
        return selectedReward_id;
    }

    /**
     * @param selectedReward_id the selectedReward_id to set
     */
    public void setSelectedReward_id(Long selectedReward_id) {
        this.selectedReward_id = selectedReward_id;
    }
    
    
    
}
